//
//  NLHomeViewModel.swift
//  sinaWeibo7110
//
//  Created by 安静清晨 on 2017/1/9.
//  Copyright © 2017年 walk-in-minds. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel
import SDWebImage

class NLHomeViewModel: NSObject {
    
    lazy var homeCellArr = [NLHomeCellViewModel]()

    //请求tableview的网络数据
    func getHomeTimeLineData (isPullUp : Bool, finished : @escaping (Bool) -> ()){
        
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //flag: 这里最好弄个guard
        guard let access_token = NLUserAccountViewModel.shared.account?.access_token else {
            return
        }
        var parameter = ["access_token" : access_token ]
        
        if isPullUp {
            
            let maxid = self.homeCellArr.last?.statuses?.id ?? 0
            
            if maxid > 0 {
                
                parameter["max_id"] = "\(maxid - 1)"
            }
        }

        print(parameter)
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameter, finished: {(resp,error)->() in
            
            if error != nil{
                
                SVProgressHUD.showError(withStatus: "网络请求失败")
                finished(false)
                return
                
            }else{
                
                //print("home_timeline数据====",resp!)
                let originDict = resp as! [String : Any]
                let statusArr = originDict["statuses"] as! [[String : Any]]//YYmodel需要提示
                //使用YYModel 将字典数组转成模型
                var tempArr = [NLHomeCellViewModel]()
                for item in statusArr{
                    
                    let cellModel = NLHomeCellViewModel()
                    let dy = NLStatusesModel()
                    
                    dy.yy_modelSet(with: item)
                    cellModel.statuses = dy
                    tempArr.append(cellModel)
                    
                }
                
                //判断是否是上拉更新, 如果是更新, 要把新下载到的20条数据加到原来的数组里
                if isPullUp{
                    
                    self.homeCellArr = self.homeCellArr + tempArr
                    
                }else{
                    
                    self.homeCellArr = tempArr
                }
                
                //在回调返回true之前把所有的单张图片下载到本地
                self.downloadSinglePictures(tempArr: tempArr, downloadImagefinished:finished)
                
                //执行成功
//                finished(true)
                
            }
            
            
        })
    
    
}


    private func downloadSinglePictures(tempArr:[NLHomeCellViewModel],downloadImagefinished: @escaping (Bool) -> ()){
        
        //要让所有单张图片都下载完毕, 才进行回调,reload tableview.
        //要保证多个异步任务全部完成, 使用调度组
        let group = DispatchGroup()
        
 
        //遍历数组, 如果有单张图片,就下载到本地
        for viewModel in tempArr{
            if viewModel.picInfos?.count == 1{
                
                
                let urlString = viewModel.picInfos?.first?.bmiddle ?? ""
                let url = URL(string: urlString)
                
                //进组
                group.enter()
               SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, saveUrl) in
                print("单张下载完毕")
                //出组
                group.leave()
                
               })
                
                
            }
            
            
        }
        
        group.notify(queue: DispatchQueue.main) {
            
            downloadImagefinished(true)
            print("全部下载完毕,已回调")
        }
        
        
    }
    

    
    
}
